<template>
  <div class="promotion-manage-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>促销活动管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateDialog">
              <el-icon><Plus /></el-icon>
              新建促销
            </el-button>
            <el-button type="success" @click="showBatchDialog">
              <el-icon><Grid /></el-icon>
              批量操作
            </el-button>
            <el-button type="warning" @click="showTemplateDialog">
              <el-icon><Document /></el-icon>
              促销模板
            </el-button>
            <el-button type="info" @click="exportPromotions">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <div class="filter-area">
        <el-form :model="filterForm" inline>
          <el-form-item label="活动名称">
            <el-input v-model="filterForm.name" placeholder="请输入活动名称" clearable />
          </el-form-item>
          <el-form-item label="活动类型">
            <el-select v-model="filterForm.type" placeholder="选择活动类型" clearable>
              <el-option label="满减活动" value="discount" />
              <el-option label="买赠活动" value="gift" />
              <el-option label="折扣活动" value="percentage" />
              <el-option label="积分活动" value="points" />
              <el-option label="会员专享" value="member" />
            </el-select>
          </el-form-item>
          <el-form-item label="活动状态">
            <el-select v-model="filterForm.status" placeholder="选择活动状态" clearable>
              <el-option label="未开始" value="pending" />
              <el-option label="进行中" value="active" />
              <el-option label="已结束" value="ended" />
              <el-option label="已暂停" value="paused" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 促销活动列表 -->
      <el-table :data="filteredPromotions" border stripe v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="活动名称" width="200" />
        <el-table-column prop="type" label="活动类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">{{ getTypeName(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="活动描述" width="250" show-overflow-tooltip />
        <el-table-column prop="startDate" label="开始时间" width="150" />
        <el-table-column prop="endDate" label="结束时间" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageCount" label="使用次数" width="100" />
        <el-table-column prop="totalDiscount" label="总优惠金额" width="120">
          <template #default="{ row }">¥{{ formatNumber(row.totalDiscount) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewPromotion(row)">查看</el-button>
            <el-button type="success" size="small" @click="editPromotion(row)">编辑</el-button>
            <el-button 
              :type="row.status === 'active' ? 'warning' : 'success'" 
              size="small" 
              @click="toggleStatus(row)"
            >
              {{ row.status === 'active' ? '暂停' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="deletePromotion(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 创建/编辑促销对话框 -->
    <el-dialog
      v-model="promotionDialogVisible"
      :title="isEdit ? '编辑促销活动' : '新建促销活动'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="promotionForm" :rules="promotionRules" ref="promotionFormRef" label-width="120px">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-form-item label="活动名称" prop="name">
              <el-input v-model="promotionForm.name" placeholder="请输入活动名称" />
            </el-form-item>
            <el-form-item label="活动类型" prop="type">
              <el-select v-model="promotionForm.type" @change="handleTypeChange" style="width: 100%">
                <el-option label="满减活动" value="discount" />
                <el-option label="买赠活动" value="gift" />
                <el-option label="折扣活动" value="percentage" />
                <el-option label="积分活动" value="points" />
                <el-option label="会员专享" value="member" />
              </el-select>
            </el-form-item>
            <el-form-item label="活动描述" prop="description">
              <el-input v-model="promotionForm.description" type="textarea" :rows="3" placeholder="请输入活动描述" />
            </el-form-item>
            <el-form-item label="活动时间" prop="dateRange">
              <el-date-picker
                v-model="promotionForm.dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="活动状态" prop="status">
              <el-radio-group v-model="promotionForm.status">
                <el-radio label="pending">未开始</el-radio>
                <el-radio label="active">进行中</el-radio>
                <el-radio label="paused">已暂停</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="活动规则" name="rules">
            <div v-if="promotionForm.type === 'discount'" class="rule-config">
              <h4>满减规则配置</h4>
              <el-form-item label="满减条件">
                <el-input-number v-model="promotionForm.rules.minAmount" :min="0" :precision="2" style="width: 200px" />
                <span class="form-tip">元</span>
              </el-form-item>
              <el-form-item label="减免金额">
                <el-input-number v-model="promotionForm.rules.discountAmount" :min="0" :precision="2" style="width: 200px" />
                <span class="form-tip">元</span>
              </el-form-item>
              <el-form-item label="最大减免">
                <el-input-number v-model="promotionForm.rules.maxDiscount" :min="0" :precision="2" style="width: 200px" />
                <span class="form-tip">元（0表示不限制）</span>
              </el-form-item>
            </div>

            <div v-else-if="promotionForm.type === 'gift'" class="rule-config">
              <h4>买赠规则配置</h4>
              <el-form-item label="购买数量">
                <el-input-number v-model="promotionForm.rules.buyQuantity" :min="1" style="width: 200px" />
                <span class="form-tip">件</span>
              </el-form-item>
              <el-form-item label="赠送数量">
                <el-input-number v-model="promotionForm.rules.giftQuantity" :min="1" style="width: 200px" />
                <span class="form-tip">件</span>
              </el-form-item>
              <el-form-item label="指定商品">
                <el-select v-model="promotionForm.rules.targetProducts" multiple placeholder="选择商品" style="width: 100%">
                  <el-option label="全部商品" value="all" />
                  <el-option label="电子产品" value="electronics" />
                  <el-option label="服装鞋帽" value="clothing" />
                  <el-option label="食品饮料" value="food" />
                </el-select>
              </el-form-item>
            </div>

            <div v-else-if="promotionForm.type === 'percentage'" class="rule-config">
              <h4>折扣规则配置</h4>
              <el-form-item label="折扣比例">
                <el-input-number v-model="promotionForm.rules.discountRate" :min="1" :max="99" style="width: 200px" />
                <span class="form-tip">折</span>
              </el-form-item>
              <el-form-item label="最低消费">
                <el-input-number v-model="promotionForm.rules.minAmount" :min="0" :precision="2" style="width: 200px" />
                <span class="form-tip">元</span>
              </el-form-item>
              <el-form-item label="最大优惠">
                <el-input-number v-model="promotionForm.rules.maxDiscount" :min="0" :precision="2" style="width: 200px" />
                <span class="form-tip">元（0表示不限制）</span>
              </el-form-item>
            </div>

            <div v-else-if="promotionForm.type === 'points'" class="rule-config">
              <h4>积分规则配置</h4>
              <el-form-item label="积分倍数">
                <el-input-number v-model="promotionForm.rules.pointsMultiplier" :min="1" :max="10" style="width: 200px" />
                <span class="form-tip">倍</span>
              </el-form-item>
              <el-form-item label="最低消费">
                <el-input-number v-model="promotionForm.rules.minAmount" :min="0" :precision="2" style="width: 200px" />
                <span class="form-tip">元</span>
              </el-form-item>
              <el-form-item label="最大积分">
                <el-input-number v-model="promotionForm.rules.maxPoints" :min="0" style="width: 200px" />
                <span class="form-tip">分（0表示不限制）</span>
              </el-form-item>
            </div>

            <div v-else-if="promotionForm.type === 'member'" class="rule-config">
              <h4>会员专享规则配置</h4>
              <el-form-item label="会员等级">
                <el-select v-model="promotionForm.rules.memberLevels" multiple placeholder="选择会员等级" style="width: 100%">
                  <el-option label="普通会员" value="normal" />
                  <el-option label="银卡会员" value="silver" />
                  <el-option label="金卡会员" value="gold" />
                  <el-option label="钻石会员" value="diamond" />
                </el-select>
              </el-form-item>
              <el-form-item label="专享折扣">
                <el-input-number v-model="promotionForm.rules.memberDiscount" :min="1" :max="99" style="width: 200px" />
                <span class="form-tip">折</span>
              </el-form-item>
              <el-form-item label="额外积分">
                <el-input-number v-model="promotionForm.rules.extraPoints" :min="0" style="width: 200px" />
                <span class="form-tip">分</span>
              </el-form-item>
            </div>
          </el-tab-pane>

          <el-tab-pane label="适用范围" name="scope">
            <el-form-item label="适用商品">
              <el-radio-group v-model="promotionForm.scope.productScope">
                <el-radio label="all">全部商品</el-radio>
                <el-radio label="category">指定分类</el-radio>
                <el-radio label="product">指定商品</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="promotionForm.scope.productScope === 'category'" label="商品分类">
              <el-select v-model="promotionForm.scope.categories" multiple placeholder="选择分类" style="width: 100%">
                <el-option label="电子产品" value="electronics" />
                <el-option label="服装鞋帽" value="clothing" />
                <el-option label="食品饮料" value="food" />
                <el-option label="日用品" value="daily" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="promotionForm.scope.productScope === 'product'" label="指定商品">
              <el-select v-model="promotionForm.scope.products" multiple placeholder="选择商品" style="width: 100%">
                <el-option label="iPhone 15" value="iphone15" />
                <el-option label="可口可乐" value="cocacola" />
                <el-option label="洗发水" value="shampoo" />
              </el-select>
            </el-form-item>
            <el-form-item label="适用客户">
              <el-radio-group v-model="promotionForm.scope.customerScope">
                <el-radio label="all">全部客户</el-radio>
                <el-radio label="member">仅会员</el-radio>
                <el-radio label="level">指定等级</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="promotionForm.scope.customerScope === 'level'" label="会员等级">
              <el-select v-model="promotionForm.scope.memberLevels" multiple placeholder="选择等级" style="width: 100%">
                <el-option label="普通会员" value="normal" />
                <el-option label="银卡会员" value="silver" />
                <el-option label="金卡会员" value="gold" />
                <el-option label="钻石会员" value="diamond" />
              </el-select>
            </el-form-item>
            <el-form-item label="使用限制">
              <el-input-number v-model="promotionForm.scope.usageLimit" :min="0" style="width: 200px" />
              <span class="form-tip">次（0表示不限制）</span>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="高级设置" name="advanced">
            <el-form-item label="优先级">
              <el-input-number v-model="promotionForm.priority" :min="1" :max="100" style="width: 200px" />
              <span class="form-tip">数字越大优先级越高</span>
            </el-form-item>
            <el-form-item label="是否互斥">
              <el-switch v-model="promotionForm.exclusive" />
              <span class="form-tip">开启后不能与其他促销同时使用</span>
            </el-form-item>
            <el-form-item label="自动启用">
              <el-switch v-model="promotionForm.autoEnable" />
              <span class="form-tip">到达开始时间自动启用</span>
            </el-form-item>
            <el-form-item label="自动结束">
              <el-switch v-model="promotionForm.autoDisable" />
              <span class="form-tip">到达结束时间自动停用</span>
            </el-form-item>
            <el-form-item label="活动备注">
              <el-input v-model="promotionForm.remark" type="textarea" :rows="3" placeholder="请输入活动备注" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      
      <template #footer>
        <el-button @click="promotionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePromotion" :loading="saveLoading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 促销详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="促销活动详情"
      width="700px"
    >
      <div v-if="currentPromotion" class="promotion-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="活动名称">{{ currentPromotion.name }}</el-descriptions-item>
          <el-descriptions-item label="活动类型">
            <el-tag :type="getTypeTagType(currentPromotion.type)">{{ getTypeName(currentPromotion.type) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="活动状态">
            <el-tag :type="getStatusTagType(currentPromotion.status)">{{ getStatusName(currentPromotion.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ currentPromotion.startDate }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ currentPromotion.endDate }}</el-descriptions-item>
          <el-descriptions-item label="使用次数">{{ currentPromotion.usageCount }}</el-descriptions-item>
          <el-descriptions-item label="总优惠金额">¥{{ formatNumber(currentPromotion.totalDiscount) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentPromotion.createTime }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider>活动描述</el-divider>
        <p>{{ currentPromotion.description }}</p>
        
        <el-divider>活动规则</el-divider>
        <div class="rule-display">
          <pre>{{ JSON.stringify(currentPromotion.rules, null, 2) }}</pre>
        </div>
      </div>
    </el-dialog>

    <!-- 批量操作对话框 -->
    <el-dialog
      v-model="batchDialogVisible"
      title="批量操作"
      width="500px"
    >
      <el-form :model="batchForm" label-width="100px">
        <el-form-item label="操作类型">
          <el-select v-model="batchForm.action" style="width: 100%">
            <el-option label="批量启用" value="enable" />
            <el-option label="批量停用" value="disable" />
            <el-option label="批量删除" value="delete" />
            <el-option label="批量导出" value="export" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择活动">
          <el-checkbox-group v-model="batchForm.selectedIds">
            <el-checkbox 
              v-for="promotion in promotions" 
              :key="promotion.id"
              :label="promotion.id"
            >
              {{ promotion.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="executeBatchAction" :loading="batchLoading">
          执行操作
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const batchLoading = ref(false)
const promotionDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const batchDialogVisible = ref(false)
const isEdit = ref(false)
const activeTab = ref('basic')
const promotionFormRef = ref()

// 当前促销
const currentPromotion = ref(null)

// 筛选表单
const filterForm = reactive({
  name: '',
  type: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 促销表单
const promotionForm = reactive({
  id: null,
  name: '',
  type: 'discount',
  description: '',
  dateRange: [],
  status: 'pending',
  rules: {
    minAmount: 0,
    discountAmount: 0,
    maxDiscount: 0,
    buyQuantity: 1,
    giftQuantity: 1,
    targetProducts: [],
    discountRate: 9,
    pointsMultiplier: 1,
    maxPoints: 0,
    memberLevels: [],
    memberDiscount: 9,
    extraPoints: 0
  },
  scope: {
    productScope: 'all',
    categories: [],
    products: [],
    customerScope: 'all',
    memberLevels: [],
    usageLimit: 0
  },
  priority: 1,
  exclusive: false,
  autoEnable: true,
  autoDisable: true,
  remark: ''
})

// 批量操作表单
const batchForm = reactive({
  action: '',
  selectedIds: []
})

// 促销活动数据
const promotions = ref([
  {
    id: 1,
    name: '满100减10',
    type: 'discount',
    description: '单笔消费满100元减10元',
    startDate: '2024-01-01 00:00:00',
    endDate: '2024-12-31 23:59:59',
    status: 'active',
    usageCount: 156,
    totalDiscount: 1560.00,
    createTime: '2024-01-01 10:00:00',
    rules: {
      minAmount: 100,
      discountAmount: 10,
      maxDiscount: 0
    }
  },
  {
    id: 2,
    name: '买二送一',
    type: 'gift',
    description: '指定商品买二送一',
    startDate: '2024-01-15 00:00:00',
    endDate: '2024-02-15 23:59:59',
    status: 'active',
    usageCount: 89,
    totalDiscount: 2670.00,
    createTime: '2024-01-15 09:00:00',
    rules: {
      buyQuantity: 2,
      giftQuantity: 1,
      targetProducts: ['electronics']
    }
  },
  {
    id: 3,
    name: '会员专享9折',
    type: 'member',
    description: '会员专享全场9折优惠',
    startDate: '2024-01-01 00:00:00',
    endDate: '2024-12-31 23:59:59',
    status: 'active',
    usageCount: 234,
    totalDiscount: 4680.00,
    createTime: '2024-01-01 08:00:00',
    rules: {
      memberLevels: ['silver', 'gold', 'diamond'],
      memberDiscount: 9,
      extraPoints: 10
    }
  }
])

// 表单验证规则
const promotionRules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' }
  ],
  dateRange: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择活动状态', trigger: 'change' }
  ]
}

// 计算属性
const filteredPromotions = computed(() => {
  let result = promotions.value

  if (filterForm.name) {
    result = result.filter(p => p.name.includes(filterForm.name))
  }
  if (filterForm.type) {
    result = result.filter(p => p.type === filterForm.type)
  }
  if (filterForm.status) {
    result = result.filter(p => p.status === filterForm.status)
  }
  if (filterForm.dateRange && filterForm.dateRange.length === 2) {
    result = result.filter(p => {
      const startDate = new Date(p.startDate)
      const endDate = new Date(p.endDate)
      const filterStart = new Date(filterForm.dateRange[0])
      const filterEnd = new Date(filterForm.dateRange[1])
      return startDate >= filterStart && endDate <= filterEnd
    })
  }

  pagination.total = result.length
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return result.slice(start, end)
})

// 方法
const getTypeTagType = (type) => {
  const typeMap = {
    'discount': 'success',
    'gift': 'warning',
    'percentage': 'primary',
    'points': 'info',
    'member': 'danger'
  }
  return typeMap[type] || 'info'
}

const getTypeName = (type) => {
  const typeMap = {
    'discount': '满减活动',
    'gift': '买赠活动',
    'percentage': '折扣活动',
    'points': '积分活动',
    'member': '会员专享'
  }
  return typeMap[type] || type
}

const getStatusTagType = (status) => {
  const statusMap = {
    'pending': 'info',
    'active': 'success',
    'ended': 'warning',
    'paused': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusName = (status) => {
  const statusMap = {
    'pending': '未开始',
    'active': '进行中',
    'ended': '已结束',
    'paused': '已暂停'
  }
  return statusMap[status] || status
}

const formatNumber = (value) => {
  if (typeof value === 'number') {
    return value.toLocaleString()
  }
  return value
}

const handleSearch = () => {
  pagination.currentPage = 1
}

const handleReset = () => {
  Object.assign(filterForm, {
    name: '',
    type: '',
    status: '',
    dateRange: []
  })
  pagination.currentPage = 1
}

const showCreateDialog = () => {
  isEdit.value = false
  resetPromotionForm()
  promotionDialogVisible.value = true
  activeTab.value = 'basic'
}

const editPromotion = (promotion) => {
  isEdit.value = true
  currentPromotion.value = promotion
  Object.assign(promotionForm, {
    ...promotion,
    dateRange: [promotion.startDate, promotion.endDate]
  })
  promotionDialogVisible.value = true
  activeTab.value = 'basic'
}

const viewPromotion = (promotion) => {
  currentPromotion.value = promotion
  detailDialogVisible.value = true
}

const deletePromotion = async (promotion) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除促销活动"${promotion.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = promotions.value.findIndex(p => p.id === promotion.id)
    if (index > -1) {
      promotions.value.splice(index, 1)
      ElMessage.success('促销活动删除成功')
    }
  } catch {
    // 用户取消删除
  }
}

const toggleStatus = (promotion) => {
  promotion.status = promotion.status === 'active' ? 'paused' : 'active'
  ElMessage.success(`促销活动已${promotion.status === 'active' ? '启用' : '暂停'}`)
}

const handleTypeChange = () => {
  // 重置规则配置
  Object.assign(promotionForm.rules, {
    minAmount: 0,
    discountAmount: 0,
    maxDiscount: 0,
    buyQuantity: 1,
    giftQuantity: 1,
    targetProducts: [],
    discountRate: 9,
    pointsMultiplier: 1,
    maxPoints: 0,
    memberLevels: [],
    memberDiscount: 9,
    extraPoints: 0
  })
}

const savePromotion = async () => {
  if (!promotionFormRef.value) return
  
  try {
    await promotionFormRef.value.validate()
    saveLoading.value = true
    
    // 模拟保存过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    if (isEdit.value) {
      // 更新促销活动
      const index = promotions.value.findIndex(p => p.id === promotionForm.id)
      if (index > -1) {
        promotions.value[index] = {
          ...promotionForm,
          startDate: promotionForm.dateRange[0],
          endDate: promotionForm.dateRange[1]
        }
      }
      ElMessage.success('促销活动更新成功')
    } else {
      // 创建新促销活动
      const newPromotion = {
        ...promotionForm,
        id: Date.now(),
        startDate: promotionForm.dateRange[0],
        endDate: promotionForm.dateRange[1],
        usageCount: 0,
        totalDiscount: 0,
        createTime: new Date().toLocaleString()
      }
      promotions.value.unshift(newPromotion)
      ElMessage.success('促销活动创建成功')
    }
    
    promotionDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saveLoading.value = false
  }
}

const resetPromotionForm = () => {
  Object.assign(promotionForm, {
    id: null,
    name: '',
    type: 'discount',
    description: '',
    dateRange: [],
    status: 'pending',
    rules: {
      minAmount: 0,
      discountAmount: 0,
      maxDiscount: 0,
      buyQuantity: 1,
      giftQuantity: 1,
      targetProducts: [],
      discountRate: 9,
      pointsMultiplier: 1,
      maxPoints: 0,
      memberLevels: [],
      memberDiscount: 9,
      extraPoints: 0
    },
    scope: {
      productScope: 'all',
      categories: [],
      products: [],
      customerScope: 'all',
      memberLevels: [],
      usageLimit: 0
    },
    priority: 1,
    exclusive: false,
    autoEnable: true,
    autoDisable: true,
    remark: ''
  })
  promotionFormRef.value?.clearValidate()
}

const showBatchDialog = () => {
  batchDialogVisible.value = true
  Object.assign(batchForm, {
    action: '',
    selectedIds: []
  })
}

const executeBatchAction = async () => {
  if (batchForm.selectedIds.length === 0) {
    ElMessage.warning('请选择要操作的活动')
    return
  }
  
  batchLoading.value = true
  
  // 模拟批量操作
  await new Promise(resolve => setTimeout(resolve, 2000))
  
  ElMessage.success(`批量${batchForm.action}操作完成`)
  batchDialogVisible.value = false
  batchLoading.value = false
}

const showTemplateDialog = () => {
  ElMessage.info('促销模板功能开发中...')
}

const exportPromotions = () => {
  ElMessage.success('促销数据导出成功')
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.promotion-manage-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.rule-config {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.rule-config h4 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.promotion-detail {
  padding: 20px 0;
}

.rule-display {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #606266;
  max-height: 200px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .filter-area .el-form {
    flex-direction: column;
  }
  
  .filter-area .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>
